package com.sisucc.contractmanage.serviceImpl.contractManageServiceImpl;


import cn.hutool.core.util.StrUtil;
import com.sisucc.contractmanage.bean.ResultModel;
import com.sisucc.contractmanage.bean.assistInfo.AssistInfoBean;
import com.sisucc.contractmanage.bean.contractInfo.ContractInfoBean;
import com.sisucc.contractmanage.constant.ReturnStatusCode;
import com.sisucc.contractmanage.dao.assistInfo.AssistInfoRepository;
import com.sisucc.contractmanage.dao.contractManage.ContractInfoRepository;
import com.sisucc.contractmanage.service.contractManageService.ContractManageService;
import com.sisucc.contractmanage.util.LocalDateTimeUtil;
import com.sisucc.contractmanage.util.PropertyUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author linyuqi
 */
@Log4j2
@Service
@Transactional
public class ContractManageServiceImpl implements ContractManageService {

    @Autowired
    private ContractInfoRepository repository;

    @Autowired
    private AssistInfoRepository assistInfoRepository;

    @Override
    public ResultModel queryContractInfo(Map<String, Object> params) throws ParseException {
        ResultModel model = new ResultModel();
        String staffCodeParam = params.get("staffCodeParam").toString();
        String staffNameParam = params.get("staffNameParam").toString();
        String contractCodeParam = params.get("contractCodeParam").toString();
        String contractNameParam = params.get("contractNameParam").toString();
        String startTimeParamSnap = params.get("startTimeParam").toString();
        String endTimeParamSnap = params.get("endTimeParam").toString();
        String accountStatusDropdownParam = params.get("accountStatusDropdownParam").toString();
        String departDropdownParam = params.get("departDropdownParam").toString();
        String contractTypeDropdownParam = params.get("contractTypeDropdownParam").toString();
        int currentPage = Integer.parseInt(params.get("currentPage").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        LocalDateTime startTimeParam = null;
        LocalDateTime endTimeParam = null;
        if (StrUtil.isNotBlank(startTimeParamSnap)) {
            startTimeParam = LocalDateTimeUtil.GMTToLocalDateTime(PropertyUtil.getStartTimeString(startTimeParamSnap));
        }
        if (StrUtil.isNotBlank(endTimeParamSnap)) {
            endTimeParam = LocalDateTimeUtil.GMTToLocalDateTime(PropertyUtil.getEndTimeString(endTimeParamSnap));
        }
        try {
            LocalDateTime finalStartTimeParam = startTimeParam;
            LocalDateTime finalEndTimeParam = endTimeParam;
            Specification<ContractInfoBean> specification =
                    (Specification<ContractInfoBean>) (root, criteriaQuery, criteriaBuilder) -> {
                        List<Predicate> predicates = new ArrayList<>();
                        if (StrUtil.isNotBlank(staffCodeParam)) {
                            predicates.add(criteriaBuilder.like(root.get("staffCode"), "%" + staffCodeParam + "%"));
                        }
                        if (StrUtil.isNotBlank(staffNameParam)) {
                            predicates.add(criteriaBuilder.like(root.get("staffName"), "%" + staffNameParam + "%"));
                        }
                        if (StrUtil.isNotBlank(contractCodeParam)) {
                            predicates.add(criteriaBuilder.equal(root.get("contractId"), contractCodeParam));
                        }
                        if (StrUtil.isNotBlank(contractNameParam)) {
                            predicates.add(criteriaBuilder.like(root.get("contractName"), "%" + contractNameParam + "%"));
                        }
                        if (Optional.ofNullable(finalStartTimeParam).isPresent()) {
                            predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), finalStartTimeParam));
                        }
                        if (Optional.ofNullable(finalEndTimeParam).isPresent()) {
                            predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), finalEndTimeParam));
                        }
                        if (StrUtil.isNotBlank(accountStatusDropdownParam)) {
                            predicates.add(criteriaBuilder.equal(root.get("contractStatus"), accountStatusDropdownParam));
                        }
                        if (StrUtil.isNotBlank(departDropdownParam)) {
                            predicates.add(criteriaBuilder.equal(root.get("departId"), departDropdownParam));
                        }
                        if (StrUtil.isNotBlank(contractTypeDropdownParam)) {
                            predicates.add(criteriaBuilder.equal(root.get("contractTypeId"), contractTypeDropdownParam));
                        }
                        Predicate[] array = new Predicate[predicates.size()];
                        return criteriaBuilder.and(predicates.toArray(array));
                    };
            Page<ContractInfoBean> contractManageBeanPage =
                    repository.findAll(specification,
                            PageRequest.of(currentPage, pageSize,
                                    Sort.by(Sort.Direction.DESC, "createTime")));
            model.getResultMap().put("total", contractManageBeanPage.getTotalElements());
            model.getResultMap().put("pages", contractManageBeanPage.getTotalPages());
            model.setResultList(contractManageBeanPage.getContent());
            log.info("动态查询合同信息---列表：" + contractManageBeanPage.getContent().toString());
            log.info("动态查询合同信息---总数：" + contractManageBeanPage.getTotalElements());
            log.info("动态查询合同信息---页数：" + contractManageBeanPage.getTotalPages());
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ERROR);
            model.setResultMessage(ReturnStatusCode.ERROR_MESSAGE);
            log.info("动态查询合同信息---程序执行失败！");
        }
        return model;
    }

    @Override
    public ResultModel saveContractInfo(Map<String, Object> params) throws ParseException {
        ResultModel model = new ResultModel();
        String uuid = (String) params.get("uuid");
        String contractName = (String) params.get("contractName");
        String deadline = (String) params.get("deadline");
        String contractStatus = (String) params.get("contractStatus");
        String accountCode = (String) params.get("accountCode");
        String staffCode = (String) params.get("staffCode");
        String staffName = (String) params.get("staffName");
        String departId = (String) params.get("departId");
        String departName = (String) params.get("departName");
        String fileGroupName = (String) params.get("fileGroupName");
        String fileName = (String) params.get("fileName");
        String fileOriginName = (String) params.get("fileOriginName");
        String annexGroupName = (String) params.get("annexGroupName");
        String annexName = (String) params.get("annexName");
        String annexOriginName = (String) params.get("annexOriginName");
        String contractTypeDropdownParam = (String) params.get("contractTypeDropdownParam");
        LocalDateTime currentDateTime = PropertyUtil.getCurrentDateTime();

        AssistInfoBean assistInfoBean = assistInfoRepository.findById(contractTypeDropdownParam).get();

        LocalDateTime deadlineParam = null;
        if (StrUtil.isNotBlank(deadline)) {
            deadlineParam = LocalDateTimeUtil.GMTToLocalDateTime(PropertyUtil.getStartTimeString(deadline));
        }
        try {
            ContractInfoBean contractInfoBean = new ContractInfoBean(uuid, contractName, contractStatus, staffCode, accountCode, staffName, departId, departName, contractTypeDropdownParam,
                    assistInfoBean.getInfoName(), fileGroupName, fileName, fileOriginName, annexGroupName, annexName, annexOriginName, currentDateTime, deadlineParam);
            log.info("添加新的合同信息" + contractInfoBean.toString());
            repository.save(contractInfoBean);
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ERROR);
            model.setResultMessage(ReturnStatusCode.ERROR_MESSAGE);
            log.info("添加新的合同信息---程序执行失败！");
        }
        return model;
    }

    @Override
    public ResultModel deleteContractInfo(Map<String, Object> params) {
        ResultModel model = new ResultModel();
        String contractId = (String) params.get("contractId");
        try {
            repository.deleteById(contractId);
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ERROR);
            model.setResultMessage(ReturnStatusCode.ERROR_MESSAGE);
            log.info("删除合同信息---程序执行失败！");
        }
        return model;
    }
}
